<!-- src/views/NoticeListView.vue -->
 <!-- 第二步：创建通知公告管理页面 -->
<template>
  <div class="notice-management">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2>通知公告管理</h2>
      <button class="btn-primary" @click="showCreateDialog = true">
        <span>+</span> 发布公告
      </button>
    </div>

    <!-- 搜索区域 -->
    <div class="filters">
      <div class="search-box">
        <input 
          v-model="searchParams.title" 
          placeholder="搜索公告标题..."
          class="search-input"
          @keyup.enter="loadNotices"
        >
        <button class="btn-search" @click="loadNotices">搜索</button>
        <button class="btn-reset" @click="resetSearch">重置</button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content-area">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <p>⏳ 正在加载公告数据...</p>
      </div>

      <!-- 公告列表 -->
      <div v-else class="notice-list">
        <div v-if="notices.length > 0" class="notices-container">
          <div v-for="notice in notices" :key="notice.id" class="notice-card">
            <div class="notice-header">
              <h3>{{ notice.title }}</h3>
              <span class="notice-date">{{ formatDate(notice.createTime) }}</span>
            </div>
            <div class="notice-content">
              <p>{{ truncateContent(notice.content) }}</p>
            </div>
            <div class="notice-footer">
              <span class="target-group">
                目标群体: {{ notice.targetGroup ? notice.targetGroup.join(', ') : '全部' }}
              </span>
              <div class="notice-actions">
                <button class="btn-view" @click="viewNotice(notice.id)">查看详情</button>
                <button class="btn-edit" @click="editNotice(notice)">编辑</button>
                <button class="btn-delete" @click="deleteNotice(notice.id)">删除</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态提示 -->
        <div v-else class="empty-state">
          <div class="empty-icon">📢</div>
          <p>暂无通知公告</p>
          <button class="btn-primary" @click="showCreateDialog = true">发布第一条公告</button>
        </div>
      </div>
    </div>

    <!-- 分页控件 -->
    <div v-if="pagination.total > 0" class="pagination">
      <button :disabled="pagination.current === 1" @click="prevPage">上一页</button>
      <span>第 {{ pagination.current }} 页 / 共 {{ pagination.pages }} 页 (共 {{ pagination.total }} 条记录)</span>
      <button :disabled="pagination.current === pagination.pages" @click="nextPage">下一页</button>
    </div>

    <!-- 公告模态框 -->
    <NoticeModal 
      v-if="showCreateDialog || editingNotice"
      :notice="editingNotice"
      @close="closeModal"
      @saved="handleNoticeSaved"
    />

    <!-- 公告详情模态框 -->
    <NoticeDetailModal 
      v-if="viewingNoticeId"
      :noticeId="viewingNoticeId"
      @close="closeDetailModal"
    />

    <!-- 操作结果提示 -->
    <div v-if="operationMessage" :class="['operation-message', operationType]">
      {{ operationMessage }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import NoticeModal from '@/components/NoticeModal.vue';
import NoticeDetailModal from '@/components/NoticeDetailModal.vue';
import { noticeApi } from '@/api/notice';

export default {
  name: 'NoticeListView',
  components: {
    NoticeModal,
    NoticeDetailModal
  },
  setup() {
    const notices = ref([]);
    const loading = ref(false);
    const showCreateDialog = ref(false);
    const editingNotice = ref(null);
    const viewingNoticeId = ref(null);
    const operationMessage = ref('');
    const operationType = ref('');
    
    const searchParams = ref({
      current: 1,
      size: 10,
      title: '',
      content: ''
    });
    
    const pagination = ref({
      current: 1,
      size: 10,
      total: 0,
      pages: 0
    });

    const loadNotices = async () => {
  loading.value = true;
  try {
    console.log('🚀 开始加载公告数据...', searchParams.value);
    const response = await noticeApi.getNotices(searchParams.value);
    console.log('📨 公告响应:', response.data);
    
    if (response.data.code === '000000') {
      const responseData = response.data.data;
      console.log('📊 响应数据内容:', responseData);
      
      // 转换 targetGroup 为数组
      const transformNotices = (notices) => {
        return notices.map(notice => {
          try {
            return {
              ...notice,
              targetGroup: notice.targetGroup ? JSON.parse(notice.targetGroup) : []
            };
          } catch (e) {
            console.error('解析 targetGroup 失败:', e);
            return {
              ...notice,
              targetGroup: []
            };
          }
        });
      };
      
      if (responseData && Array.isArray(responseData.data)) {
        notices.value = transformNotices(responseData.data);
        pagination.value.total = responseData.total || 0;
        pagination.value.current = responseData.currentPage || 1;
        pagination.value.pages = Math.ceil(pagination.value.total / searchParams.value.size);
      } else if (Array.isArray(responseData)) {
        notices.value = transformNotices(responseData);
        pagination.value.total = responseData.length;
        pagination.value.pages = 1;
      } else {
        console.warn('⚠️ 无法解析的数据结构，使用备用方案');
        notices.value = getMockData();
      }
    } else {
      console.error('❌ API返回错误:', response.data.msg);
      notices.value = getMockData();
    }
  } catch (error) {
    console.error('💥 加载公告列表失败:', error);
    notices.value = getMockData();
  } finally {
    loading.value = false;
  }
};

    // 模拟数据备用
    const getMockData = () => {
      return [
        {
          id: 1,
          title: '系统维护通知',
          content: '系统将于2024年1月20日进行维护升级，预计停机2小时。',
          targetGroup: ['admin', 'teacher', 'student'],
          createTime: '2024-01-15T10:00:00',
          expireTime: '2024-01-20T23:59:59'
        },
        {
          id: 2,
          title: '期末考试安排',
          content: '本学期期末考试将于2024年1月25日开始，请各位同学做好准备。',
          targetGroup: ['student'],
          createTime: '2024-01-10T14:30:00',
          expireTime: '2024-01-25T23:59:59'
        }
      ];
    };

    const truncateContent = (content, maxLength = 100) => {
      if (!content) return '';
      if (content.length <= maxLength) return content;
      return content.substring(0, maxLength) + '...';
    };

    const formatDate = (dateString) => {
      if (!dateString) return '';
      try {
        return new Date(dateString).toLocaleDateString('zh-CN');
      } catch (error) {
        return dateString;
      }
    };

    const viewNotice = (id) => {
      viewingNoticeId.value = id;
    };

    const editNotice = (notice) => {
      editingNotice.value = { ...notice };
    };

    const deleteNotice = async (id) => {
      if (confirm('确定要删除这个公告吗？此操作不可恢复。')) {
        try {
          const response = await noticeApi.deleteNotice(id);
          if (response.data.code === '000000') {
            showMessage('删除成功！');
            loadNotices();
          } else {
            throw new Error(response.data.msg);
          }
        } catch (error) {
          console.error('❌ 删除公告失败:', error);
          const errorMsg = error.response?.data?.message || error.message || '删除失败';
          showMessage(`删除失败: ${errorMsg}`, 'error');
        }
      }
    };

    const resetSearch = () => {
      searchParams.value.title = '';
      searchParams.value.content = '';
      searchParams.value.current = 1;
      loadNotices();
    };

    const closeModal = () => {
      showCreateDialog.value = false;
      editingNotice.value = null;
    };

    const closeDetailModal = () => {
      viewingNoticeId.value = null;
    };

    const handleNoticeSaved = () => {
      closeModal();
      loadNotices();
      showMessage('操作成功！');
    };

    const prevPage = () => {
      if (searchParams.value.current > 1) {
        searchParams.value.current--;
        loadNotices();
      }
    };

    const nextPage = () => {
      if (searchParams.value.current < pagination.value.pages) {
        searchParams.value.current++;
        loadNotices();
      }
    };

    const showMessage = (message, type = 'success') => {
      operationMessage.value = message;
      operationType.value = type;
      setTimeout(() => {
        operationMessage.value = '';
        operationType.value = '';
      }, 3000);
    };

    onMounted(() => {
      console.log('📍 NoticeListView组件已挂载');
      loadNotices();
    });

    return {
      notices,
      loading,
      searchParams,
      pagination,
      showCreateDialog,
      editingNotice,
      viewingNoticeId,
      operationMessage,
      operationType,
      loadNotices,
      truncateContent,
      formatDate,
      viewNotice,
      editNotice,
      deleteNotice,
      resetSearch,
      closeModal,
      closeDetailModal,
      handleNoticeSaved,
      prevPage,
      nextPage
    };
  }
};
</script>

<style scoped>
.notice-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filters {
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 300px;
}

.btn-primary, .btn-search, .btn-reset {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-search {
  background-color: #2ecc71;
  color: white;
}

.btn-reset {
  background-color: #95a5a6;
  color: white;
}

.main-content-area {
  min-height: 500px;
}

.loading-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.notices-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.notice-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.notice-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.notice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.notice-header h3 {
  margin: 0;
  color: #2c3e50;
}

.notice-date {
  color: #7f8c8d;
  font-size: 14px;
}

.notice-content {
  margin-bottom: 15px;
  color: #34495e;
  line-height: 1.6;
}

.notice-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.target-group {
  font-size: 12px;
  color: #7f8c8d;
  background: #f8f9fa;
  padding: 4px 8px;
  border-radius: 4px;
}

.notice-actions {
  display: flex;
  gap: 8px;
}

.btn-view, .btn-edit, .btn-delete {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.btn-view {
  background-color: #3498db;
  color: white;
}

.btn-edit {
  background-color: #ff9800;
  color: white;
}

.btn-delete {
  background-color: #e74c3c;
  color: white;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

.pagination button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.operation-message {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 15px 20px;
  border-radius: 4px;
  color: white;
  font-weight: 500;
  z-index: 1000;
}

.operation-message.success {
  background: #27ae60;
}

.operation-message.error {
  background: #e74c3c;
}

@media (max-width: 768px) {
  .notices-container {
    grid-template-columns: 1fr;
  }
  
  .search-box {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    min-width: auto;
  }
}
</style>